package com.ruoyi.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * 打印controller的URL
 */
@Component
public class StartupConfig implements CommandLineRunner {

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;

    @Override
    public void run(String... args) throws Exception {
        printRequestMappings();
    }

    /**
     * 打印出项目中所有的url请求地址和方法的映射关系
     */
    public void printRequestMappings() {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo info = entry.getKey();
            HandlerMethod method = entry.getValue();
            Method targetMethod = method.getMethod();
            String urlPath = "";
            if (info.getPathPatternsCondition() != null) {
                Set<String> patternValues = info.getPathPatternsCondition().getPatternValues();
                for (String pattern : patternValues) {
                    urlPath = pattern;
                }
            }
            String httpMethod = "";
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            for (RequestMethod requestMethod : methods) {
                httpMethod = requestMethod.name();
            }
            System.out.println("URL Path: " + urlPath + ", HTTP Method: " + httpMethod + " (" + targetMethod.getName() + ")");
        }
    }

}
